# TODO: Add comment
# 
# Author: guochun
###############################################################################


pSizeTor=function(samples){
	N=numeric()
	sampleMethod=attr(samples,"sampleMethod")
	spclass=class(sampleMethod)
	
	if(class(samples)=="population"){	
		#delete the potential NA in samples
		sps=samples@samples[!is.na(samples@samples)]
		n=length(sps)
		
		if( spclass== "eToe" | spclass == "pToe"){
			N=n/pi/sum((unlist(lapply(sps, function(x) x[1,5])))^2)*prod(samples@plotdim)
		}else if(spclass == "tSquare"){
			N=n*2/pi/sum((unlist(lapply(sps, function(x) x[1,8])))^2)*prod(samples@plotdim)
		}else if(spclass == "pQuarter"){
			nn=unlist(lapply(sps, function(x) x[1,c(5,8,11,14)]))
			nn=nn[nn!=Inf]
			N=4*(length(nn)-1)/pi/sum((nn)^2)*prod(samples@plotdim)
		}
	}else{
		plotdim=attr(samples,"plotdim")
		if(spclass=="angleOrder"){
			n=sampleMethod@n
			q=sampleMethod@q
			k=sampleMethod@k
			if(!sampleMethod@composite){
				N=q*(q*n*k-1)/pi/sum(samples^2)*prod(plotdim)
			}else{
				n=n/2
				N=q/pi/sqrt(sum((samples[[1]])^2)*sum((samples[[2]])^2))*
						exp(2*lgamma(n*q*k)-2*lgamma(n*q*k-1/2))*prod(plotdim)
			}
			
			return(N)
		}
		#delete the potential NA in samples
		if(spclass == "diggleCp"){
			d2=attr(samples,"d2")
			d2=d2[!is.na(d2)]
		}
		samples=samples[!is.na(samples)]
		n=length(samples)
		#browser()
		if(length(samples)==0){
			N=NA
		}else if(spclass == "eToe" ){
			    N=(n*sampleMethod@k-1)/pi/sum((samples)^2)*prod(plotdim)
		}else if( spclass == "pToe"){
			#define the numparametric estimator
			if(sampleMethod@nonparametric){
				N=(n^(2/3)-1)/n/pi/(sort(samples)[ceiling(n^(2/3))])^2*prod(plotdim)
			}else{
				N=(n*sampleMethod@k-1)/pi/sum((samples)^2)*prod(plotdim)
			}
		}else if(spclass == "tSquare"){
			#browser()
			if(sampleMethod@composite)
			    N=(n/2)^2/2/sqrt(2)/sum(samples[1:(n/2)])/sum(samples[(n/2+1):n])*prod(plotdim)
			else
			    N=(2*n*sampleMethod@k-1)/pi/sum((samples)^2)*prod(plotdim)
		}else if(spclass == "pQuarter"){
			if(sampleMethod@k == 1){
				N=4*(n-1)/pi/sum((samples)^2)*prod(plotdim)
			}else{
				N=(sampleMethod@k-1)/pi/round(n/4)*sum(1/samples^2)*prod(plotdim)
			}
		}else if(spclass == "diggleCp"){
			#browser()
			N1=(n*sampleMethod@k-1)/pi/sum((samples)^2)*prod(plotdim)
			N2=(n*sampleMethod@k-1)/pi/sum((d2)^2)*prod(plotdim)
			N=sqrt(N1*N2)
		}
			
	}

	return(N)
}

